<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useBookStore } from '@/stores/book';
import { ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const bookStore = useBookStore();

// 判断是新增还是编辑
const isEdit = computed(() => !!route.params.id);
const pageTitle = computed(() => isEdit.value ? '编辑图书' : '新增图书');

// 表单数据
const bookForm = ref({
  id: null,
  title: '',
  author: '',
  description: '',
  category: '',
  price: 0,
  isbn: '',
  publishDate: '',
  coverUrl: ''
});

// 表单规则
const rules = {
  title: [
    { required: true, message: '请输入图书标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ]
};

const formRef = ref(null);
const loading = ref(false);

// 计算属性
const categories = computed(() => bookStore.categories);

// 处理图片URL
const handleImageUrl = (url) => {
  if (!url) return '';
  // 如果是相对路径，添加基础URL
  if (!url.startsWith('http')) {
    return `${import.meta.env.VITE_API_BASE_URL || ''}${url}`;
  }
  return url;
};

// 加载图书详情
const loadBookDetail = async (id) => {
  loading.value = true;
  try {
    const book = await bookStore.fetchBookById(id);
    console.log('图书详情数据:', book);
    if (book) {
      // 深拷贝对象属性
      bookForm.value = JSON.parse(JSON.stringify(book));
      
      // 处理日期格式
      if (book.publishDate) {
        bookForm.value.publishDate = book.publishDate.substring(0, 10);
      }
      
      // 处理创建时间和修改时间
      if (book.gmtCreate) {
        console.log('原始创建时间:', book.gmtCreate);
      }
      
      // 确保图片URL正确
      if (book.coverUrl) {
        console.log('图片URL:', book.coverUrl);
        // 如果是相对路径，添加基础URL
        if (book.coverUrl && !book.coverUrl.startsWith('http')) {
          bookForm.value.coverUrl = `${import.meta.env.VITE_API_BASE_URL}${book.coverUrl}`;
        }
      }
    }
  } catch (error) {
    console.error('加载图书详情失败:', error);
    ElMessage.error('加载图书详情失败');
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (isEdit.value) {
          // 编辑图书
          await bookStore.editBook(bookForm.value.id, bookForm.value);
          ElMessage.success('更新成功');
        } else {
          // 新增图书
          await bookStore.addBook(bookForm.value);
          ElMessage.success('添加成功');
        }
        // 返回列表页
        router.push('/books');
      } catch (error) {
        console.error('保存图书失败:', error);
        ElMessage.error('保存图书失败');
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.warning('请正确填写表单');
      return false;
    }
  });
};

// 取消操作
const cancelForm = () => {
  router.push('/books');
};

onMounted(() => {
  // 如果是编辑模式，加载图书详情
  if (isEdit.value) {
    loadBookDetail(route.params.id);
  }
});
</script>

<template>
  <div class="book-edit-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>{{ pageTitle }}</h2>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="bookForm"
        :rules="rules"
        label-width="100px"
        v-loading="loading">
        
        <el-form-item label="图书标题" prop="title">
          <el-input v-model="bookForm.title" placeholder="请输入图书标题" />
        </el-form-item>
        
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" placeholder="请输入作者" />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="bookForm.category" placeholder="请选择分类" style="width: 100%;">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="bookForm.price" :precision="2" :step="0.1" :min="0" style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="bookForm.isbn" placeholder="请输入ISBN" />
        </el-form-item>
        
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
            v-model="bookForm.publishDate"
            type="date"
            placeholder="选择出版日期"
            style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="封面图片" prop="coverUrl">
          <div class="cover-upload">
            <el-input 
              v-model="bookForm.coverUrl" 
              placeholder="请输入封面图片URL" 
              style="margin-bottom: 10px;" />
            <div v-if="bookForm.coverUrl" class="cover-preview">
              <el-image
                :src="handleImageUrl(bookForm.coverUrl)"
                fit="cover"
                style="width: 120px; height: 160px; border-radius: 4px;"
                :preview-src-list="[handleImageUrl(bookForm.coverUrl)]"
                :preview-teleported="true">
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <div>图片加载失败</div>
                  </div>
                </template>
              </el-image>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="bookForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入图书描述" />
        </el-form-item>

        <el-form-item label="创建时间" v-if="isEdit && bookForm.gmtCreate">
          <el-input v-model="bookForm.gmtCreate" disabled />
        </el-form-item>

        <el-form-item label="修改时间" v-if="isEdit && bookForm.gmtModified">
          <el-input v-model="bookForm.gmtModified" disabled />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.book-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cover-upload {
  width: 100%;
}

.cover-preview {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 160px;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
  font-size: 14px;
  border-radius: 4px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}
</style>
